package top.went.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import top.went.aop.SystemLog;
import top.went.exception.InputException;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.DeliverDetailEntity;
import top.went.pojo.OrderDetailEntity;
import top.went.pojo.OrderEntity;
import top.went.pojo.UserEntity;
import top.went.service.*;
import top.went.utils.CheckForm;
import top.went.vo.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 订单控制器
 */
@Controller
@RequestMapping("/sale/order")
@ResponseBody
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private WarehouseSend warehouseSend;
    @Autowired
    private ApprovalService approvalService;
    @Autowired
    private ReceiptRecordsService receiptRecordsService;
    @Autowired
    private PlanPayBackService planPayBackService;
    @Autowired
    private PayBackDetailService payBackDetailService;
    @Autowired
    private ReturnGoodsService returnGoodsService;

    /**
     * 加载所有数据
     * @param orderSearch
     * @return
     */
    @RequestMapping("/all")
    public PageEntity<OrderVo> findAll(@RequestBody  OrderSearch orderSearch){
        System.out.println("我的分割线"+orderSearch.getCusId());
        return orderService.findAll(orderSearch);
    }
    /**
     * 加载所有数据
     * @param orderSearch
     * @return
     */
    @RequestMapping("/detail/all")
    public PageEntity<OrderDetail> findAll(OrderDetailSearch orderSearch){
        return orderService.findAll(orderSearch);
    }

    /**
     * 加载订单信息
     * @param id
     * @return
     * @throws InputException
     * @throws NotFoundException
     */
    @RequestMapping("/load")
    public Code load(Long id) throws InputException, NotFoundException {
        if (id == null || id.toString().length() <=0)
            throw new InputException("订单信息错误");
        return Code.success(orderService.loadBy(id));
    }
    /**
     * 添加合同
     * @param orderEntity
     * @return
     */
    @PostMapping("/contract/save")
    @SystemLog(module = "合同订单",methods = "添加合同")
    public Code addContract(OrderEntity orderEntity) throws ServiceException, NotFoundException, InputException {
        if (orderEntity == null)
            throw new InputException("请输入合同信息");
        orderEntity.setLoginDelete(false);
        orderEntity.setOrderType(false);
        CheckForm.checkContract(orderEntity);
        if (orderEntity.getOrderId() == null || orderEntity.getOrderId().toString().length() <=0){
            orderService.addOrder(orderEntity);
            return Code.success("添加合同成功");
        }else {
            orderService.modifyOrder(orderEntity,false);
            return Code.success("修改合同成功");
        }
    }

    /**
     * 添加订单
     * @param orderEntity
     * @return
     */
    @PostMapping("/save")
    @SystemLog(module = "合同订单",methods = "添加订单")
    public Code addOrder(OrderEntity orderEntity) throws ServiceException, NotFoundException, InputException {
        if (orderEntity == null)
            throw new InputException("请输入订单信息");
        orderEntity.setLoginDelete(false);
        orderEntity.setOrderType(true);
        CheckForm.checkContract(orderEntity);
        if (orderEntity.getOrderId() == null || orderEntity.getOrderId().toString().length() <=0){
            orderService.addOrder(orderEntity);
            return Code.success("添加订单成功");
        }else {
            orderService.modifyOrder(orderEntity,true);
            return Code.success("修改订单成功");
        }
    }

    /**
     * 删除合同/订单
     * @param id
     * @return
     * @throws InputException
     * @throws NotFoundException
     * @throws ServiceException
     */
    @RequestMapping("/delete")
    @SystemLog(module = "合同订单",methods = "删除合同/订单")
    public Code delete(Long id) throws InputException, NotFoundException, ServiceException {
        if (id == null || id.toString().length() <=0){
            throw new InputException("合同/订单信息错误");
        }
        orderService.deleteOrder(id);
        return Code.success("删除合同/订单成功");
    }

    /**
     * 批量删除合同/订单
     * @param ids
     * @return
     * @throws InputException
     * @throws NotFoundException
     * @throws ServiceException
     */
    @RequestMapping("/deleteall")
    @SystemLog(module = "合同订单",methods = "批量删除合同/订单")
    public Code deleteAll(@RequestParam("ids[]") Long[] ids) throws InputException, NotFoundException, ServiceException {
        if (ids.length <=0){
            throw new InputException("合同/订单信息错误");
        }
        orderService.deleteAll(ids);
        return Code.success("删除合同/订单成功");
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @RequestMapping("/info/{id}/")
    public ModelAndView info(@PathVariable("id") Long id){
        return getModelAndView(id,"sale/contractInfo","sale/orderInfo");
    }

    private ModelAndView getModelAndView(@PathVariable("id") Long id, String s, String s1) {
        ModelAndView modelAndView = new ModelAndView();
        if (id == null)
            return  new ModelAndView("404");
        try {
            OrderVo order = orderService.loadBy(id);
            if (order == null)
                return new ModelAndView("404");


            if (order.getOrderType()!=null&&order.getOrderType()) {
                modelAndView.setViewName(s1);
                modelAndView.addObject("sends",warehouseSend.loadSendByOrder(id));
                List<ReturnGoodsVO> returnGoodsVO= returnGoodsService.findAll(new ReturnGoodsVO(id)).getRows();
                if (returnGoodsVO.size() >0)
                    order.setReturnGoods("有退货");
                modelAndView.addObject("returnGoodsVOS",returnGoodsVO);
            }
            else {
                modelAndView.setViewName(s);
                modelAndView.addObject("details",orderService.loadDeatil(order.getOrderId().longValue()));
                modelAndView.addObject("sends",warehouseSend.loadDetailSendByOrder(order.getOrderId().longValue()));
            }
            modelAndView.addObject("info",order);
            modelAndView.addObject("approvals",approvalService.findApprovalById(id.intValue(),"订单"));
            modelAndView.addObject("moneyPlan",planPayBackService.findAllByManyConditions(new PlanPayBackVO(id.intValue())).getRows());
            modelAndView.addObject("moneyLogs",payBackDetailService.findAllByManyConditions(new PayBackDetailVO(id.intValue())).getRows());
            modelAndView.addObject("money",receiptRecordsService.findAllByManyConditions(new ReceiptRecordsVO(id.intValue())).getRows());

        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("404");
        }
        return modelAndView;
    }

    /**
     * 订单详情页面
     * @param id
     * @return
     */
    @RequestMapping("/detail/{id}/")
    public ModelAndView detailInfo(@PathVariable("id") Long id){
        return getModelAndView(id,"404","sale/orderDeatil");
    }

    /**
     * 修改订单状态
     * @param id
     * @param orderStatus
     * @return
     * @throws InputException
     */
    @PostMapping("/status")
    @SystemLog(module = "合同订单",methods = "修改订单状态")
    public Code changeStatus(Long id, Long orderStatus) throws InputException, NotFoundException, ServiceException {
        if (id == null || orderStatus == null || (orderStatus!=0&&orderStatus!=1&&orderStatus!=2))
            throw new InputException("输入信息错误");
        orderService.modifyStatus(id,orderStatus);
        return Code.success();
    }

    /**
     * 加载订单明细数据
     * @param id
     * @return
     * @throws InputException
     */
    @RequestMapping("/detail")
    public List<OrderDetail> loadDeatil(Long id) throws InputException {
        if (id == null || id.toString().length() <=0)
            throw new InputException("订单信息错误");
        return orderService.loadDeatil(id);
    }

    /**
     * 添加交付计划模态框
     * @param id
     * @return
     * @throws NotFoundException
     */
    @RequestMapping("/detail/addOne/modal")
    public ModelAndView addDetail(Long id) throws NotFoundException {
        ModelAndView m = new ModelAndView("/sale/modal/add_order_detail");
        OrderVo orderVo = orderService.loadBy(id);
        if (orderVo.getOrderType())
            throw new NotFoundException("合同错误");
        m.addObject("order",orderVo);
        return m;
    }

    /**
     * 添加交付记录模态框
     * @param id
     * @return
     * @throws NotFoundException
     */
    @RequestMapping("/send/addOne/modal")
    public ModelAndView addSend(Long id) throws NotFoundException {
        ModelAndView m = new ModelAndView("/sale/modal/add_order_send");
        OrderVo orderVo = orderService.loadBy(id);
        if (orderVo.getOrderType())
            throw new NotFoundException("合同错误");
        m.addObject("order",orderVo);
        return m;
    }


    /**
     * 保存订单明细数据
     * @param orderDetailVo
     * @return
     */
    @PostMapping("/detail/save")
    @SystemLog(module = "合同订单",methods = "修改订单明细")
    public Code saveDetail(OrderDetailVo orderDetailVo) throws InputException, NotFoundException, ServiceException {
        if (orderDetailVo.getId() == null)
            throw new InputException("订单信息错误");
        List<OrderDetailEntity> detailEntities = orderDetailVo.getDatas();
        CheckForm.checkOrderDetail(detailEntities);
        orderService.addDetail(detailEntities,orderDetailVo.getId());
        return Code.success();
    }

    /**
     * 添加交付计划
     * @param detailEntity
     * @return
     * @throws InputException
     * @throws NotFoundException
     * @throws ServiceException
     */
    @PostMapping("/detail/addOne")
    @SystemLog(module = "合同订单",methods = "添加交付计划")
    public Code addOneDetaill(OrderDetailEntity detailEntity) throws InputException, NotFoundException, ServiceException {
        CheckForm.checkOrderDetailOne(detailEntity);
        orderService.addOneDetail(detailEntity);
        return Code.success();
    }

    /**
     * 添加交付记录
     * @param deliverDetailEntity
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     * @throws InputException
     */
    @PostMapping("/send/addOne")
    public Code addOneSend(DeliverDetailEntity deliverDetailEntity) throws NotFoundException, ServiceException, InputException {
        CheckForm.checkSendDetailOne(deliverDetailEntity);
        warehouseSend.addOneSend(deliverDetailEntity);
        return Code.success();
    }
}
